import { Layout, Menu, theme, Flex, Typography, Button, Space, } from "antd";
import { relative } from "path";
import React, { useState } from 'react';
const { Header, Content, Footer, Sider } = Layout;
import { Sender, Bubble, useXAgent, useXChat } from '@ant-design/x';
import { UserOutlined, SyncOutlined, CopyOutlined, OpenAIOutlined } from '@ant-design/icons';
import OpenAI from 'openai';
import markdownit from 'markdown-it';

// 配置信息
const apikey = 'sk-68ac5f5ccf3540ba834deeeaecb48987'
const baseUrl = 'https://dashscope.aliyuncs.com/compatible-mode/v1'
const modelName = 'qwen-plus'

// 初始化模型实例
const client = new OpenAI({
    baseURL: baseUrl,
    apiKey: apikey,
    dangerouslyAllowBrowser: true,
});

const md = markdownit({ html: true, breaks: true });

const fooAvatar = {
    color: '#f56a00',
    backgroundColor: '#fde3cf',
};
const barAvatar = {
    color: '#fff',
    backgroundColor: '#87d068',
};
const hideAvatar: any = {
    visibility: 'hidden',
};

function Home() {
    const [collapsed, setCollapsed] = useState(false);
    const [searchLoading, setSearchLoading] = useState(false);
    const [searchText, setSearchText] = useState('');
    
    const [agent] = useXAgent({
        request: async (info, callbacks: any) => {
            const { messages, message } = info;
            const { onSuccess, onUpdate, onError } = callbacks;
            let content: string = '';
            let aiMessageComplete = false; // 标记AI消息是否接收完整
    
            try {
                const stream = await client.chat.completions.create({
                    model: modelName,
                    messages: [{ role: 'user', content: `${message}` }],
                    stream: true,
                });
    
                for await (const chunk of stream) {
                    const responseText = chunk.choices[0]?.delta?.content || '';
                    content += responseText;

                    // 如果流式最后接受到空字符串，为截止
                    if (responseText === '' && content.trim() !== '') {
                        aiMessageComplete = true;
                        setSearchLoading(false)
                    }

                    onUpdate(content);
                }
                
                onSuccess(content);
            } catch (error) {
                console.log('error:', error);
            }
        },
    });

    const { onRequest, messages, } = useXChat({ agent });

    // 调大模型接口
    const handleSearch = (text: any) => {
        onRequest(text)
    }

    const renderMarkdown = (content: any) => (
        <Typography>
            <div dangerouslySetInnerHTML={{ __html: md.render(content) }} />
        </Typography>
    );
    
    return (
        <div className="App">
            <Layout
                style={{
                    minHeight: '100vh',
                }}
            >
                <Sider 
                    collapsible 
                    collapsed={collapsed} 
                    onCollapse={(value) => setCollapsed(value)}
                    style={{
                        backgroundColor: '#ebeffa',
                    }}
                >
                    <div>左侧栏</div>
                </Sider>

                <Layout>
                    <Content>
                        <div style={{height: '100vh', backgroundColor: '#f4f6fc',}}>
                            <div style={{width: '1200px', height: '100vh', padding: '80px 100px', margin: '0 auto', position: 'relative'}}>
                                {/* 对话区 */}
                                <div>
                                    <Flex gap="middle" vertical>
                                        {
                                            messages.map((item: any) => {
                                                return <Bubble
                                                            key={item.id}
                                                            placement={item.status === 'local' ? 'end' : 'start'}
                                                            content={renderMarkdown(item.message)}
                                                            // content={item.message}
                                                            avatar={{
                                                                icon: <UserOutlined />,
                                                                style: item.status === 'local' ? barAvatar : fooAvatar,
                                                            }}
                                                            // footer={
                                                            //     item.status === 'local' ? null : 
                                                            //     <Space>
                                                            //         <Button color="default" variant="text" size="small" icon={<SyncOutlined />} />
                                                            //         <Button color="default" variant="text" size="small" icon={<CopyOutlined />} />
                                                            //     </Space>
                                                            // }
                                                        />
                                                }
                                            )
                                        }
                                    </Flex>
                                </div>  

                                {/* 提问区 */}
                                <div style={{width: '1000px', position: 'absolute', bottom: '80px'}}>
                                    <Sender
                                        placeholder="Press Shift + Enter to send message"
                                        loading={searchLoading}
                                        value={searchText}
                                        onChange={(v) => {
                                            setSearchText(v)
                                        }}
                                        onSubmit={() => {
                                            setSearchLoading(true);
                                            handleSearch(searchText)
                                            setSearchText('')
                                        }}
                                        onCancel={() => {
                                            setSearchLoading(false);
                                        }}
                                    />
                                </div>
                            </div>
                        </div>
                    </Content>
                </Layout>
            </Layout>
        </div>
    );
}

export default Home;
